/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof.wget;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Carlos Pinheiro
 */
public class ParsersLauncher extends Thread
{
    private static final int WAIT_TIME = 1000;
    private ExecutorService tpParsers = Executors.newCachedThreadPool();
    
    private static ParsersLauncher lb = new ParsersLauncher();

    private ParsersLauncher()
    {
    }

    public static ParsersLauncher getInstance()
    {
        return lb;
    }

    @Override
    public void run()
    {
        // Starts parsers controller
        ParsersBalancers.getInstance().start();
        
        try
        {
            tpParsers = Executors.newCachedThreadPool();
            while (!isInterrupted())
            {
                if (ToParseQueue.getInstance().isEmpty())
                {
                    Thread.sleep(WAIT_TIME);
                    continue;
                }
                
                Runnable parser = new ParserExecutor();
                tpParsers.execute(parser);
            }
        }
        catch (InterruptedException ex)
        {            
        }
        finally
        {
            processInterruption();
        }
    }
    
    private void processInterruption()
    {            
        try
        {
            ParsersBalancers.getInstance().interrupt();
            ParsersBalancers.getInstance().join();
            
            tpParsers.shutdown();
            tpParsers.awaitTermination(10, TimeUnit.SECONDS);
        }
        catch (InterruptedException ex)
        {
        }
    }
}
